package com.zlp.mall.security.component;

import cn.hutool.json.JSONUtil;
import com.zlp.mall.common.api.R;
import com.zlp.mall.common.api.RespCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 *  没有登录时的响应
 * @since 2021-10-26 17:12:19
 */
public class RestfulAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException{
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        // 响应401 暂未登录或session已经过期
        response.getWriter().println(JSONUtil.parse(R.failed(RespCode.UNAUTHORIZED)));
        response.getWriter().flush();
    }
}
